// Learn cc.Class:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] https://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //     // ATTRIBUTES:
        //     default: null,        // The default value will be used only when the component attaching
        //                           // to a node for the first time
        //     type: cc.SpriteFrame, // optional, default is typeof default
        //     serializable: true,   // optional, default is true
        // },
        // bar: {
        //     get () {
        //         return this._bar;
        //     },
        //     set (value) {
        //         this._bar = value;
        //     }
        // },
        player:{type:cc.Sprite,default: null},
        bg:{type:cc.Node,default: null},
        leftFloorLayer:{type:cc.Node,default: null},
        rightFloorLayer:{type:cc.Node,default: null},
        touch:{type:cc.Component,default: null},
        floorPrefab:{type:cc.Prefab,default: null},
        leftFloorSpriteFrame:{type:cc.SpriteFrame,default:null},
        rightFloorSpriteFrame:{type:cc.SpriteFrame, default:null},
        leftSpeed: 2,
        rightSpeed: 3,
        bgSpeed: 10,
        playerJumpSpeed:1,
        scoreLabel:{type:cc.Label, default: null},
        overLalbe:{type:cc.Label, default: null},
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this.STATUS = {LEFT : 0 ,RIGHT : 1 ,}; 
        this.gameHeight = 960;
        this.isJump = false;
        this.rateSpeed = 1;
        this.reSpeed = 0;
        this.addSpeed = 0;
        this.currentSpeed = 0;
        this.gameStatus = this.STATUS.RIGHT;
        this.leftFloorList = [];
        this.rightFloorList = [];
        this.colFloor = null;
        this.gameOver = false;
        this.leftFloorPosSet = [-702,-506,-301,-114,82,278,474,670];
        this.rightFloorPosSet = [-670,-482,-294,-106,82,270,458,646];
        this.jumpAction = null;
        this.score = 0;

        this.overLalbe.node.active = false;
        cc.director.getCollisionManager().enabled = true;
        //cc.director.getCollisionManager().enabledDebugDraw = true;

        //cc.Node.EventType.TOUCH_START
        this.touch.node.on(cc.Node.EventType.TOUCH_START,this.onTouchEvent,this);
        this.player.node.on('playerCollision', this.onPlayerCollision,this);
       
        //初始化对象
        this.floorPool = new cc.NodePool();
        let initCount = 8;
        for (let i = 0; i < initCount; i++) {
            let leftFloor = this.createFloor();//左边的
            leftFloor.tempTag = this.STATUS.LEFT;
            // leftFloor.getComponent(cc.Sprite).spriteFrame = this.leftFloorSpriteFrame;
            leftFloor.y = this.leftFloorPosSet[i];
            this.leftFloorLayer.addChild(leftFloor,i);
            this.leftFloorList[i] = leftFloor;

            let rightFloor = this.createFloor();//右边
            rightFloor.tempTag = this.STATUS.RIGHT;
            rightFloor.getComponent(cc.Sprite).spriteFrame = this.rightFloorSpriteFrame;
            rightFloor.y = this.rightFloorPosSet[i];
            this.rightFloorLayer.addChild(rightFloor,i);
            this.rightFloorList[i] = rightFloor;
        }
    },

    onPlayerCollision(other){
        console.log("other.tag = ", other.tag);
        if(other.tag == 1)//游戏结束
        {
            this.gameOver = true;
            this.overLalbe.node.active = true;
            this.player.node.stopAllActions();
        }else if(other.tag == 2)//确定跳到的格子
        {
            this.colFloor = other.node;
            this.gameStatus = other.node.tempTag;
        }else if(other.tag == 0)//
        {
            this.isJump = false;
            this.colFloor = other.node;
            this.gameStatus = other.node.tempTag;
        }
    },

    createFloor:function(){
        let floor = null;
        if (this.floorPool.size() > 0) { // 通过 size 接口判断对象池中是否有空闲的对象
            floor = this.floorPool.get();
        } else { 
            // 如果没有空闲对象，也就是对象池中备用对象不够时，我们就用 cc.instantiate 重新创建
            floor = cc.instantiate(this.floorPrefab);
        }
         // this.floorPool.put(floor); // 通过 put 接口放入对象池
        // floor.parent = parentNode; // 将生成的敌人加入节点树
        // floor.getComponent(cc.Sprite).spriteFrame = spriteFrame;
        return floor;
    },

    onTouchEvent:function(event){
        if(this.isJump == false)
        {
            let action;
            // this.player.node.x += 10;
            if(this.gameStatus == this.STATUS.LEFT)
            {
                //目前站在左边
                action = cc.jumpTo(this.playerJumpSpeed, cc.v2(51, 58), 5, 1);
            }else
            {
                //目前站在右边
                action = cc.jumpTo(this.playerJumpSpeed, cc.v2(-119, 58), 5, 1);
            }
            // console.log('Mouse down ================   '+ this.gameStatus);
            this.jumpAction = cc.sequence(action, cc.callFunc(this.onJumpComplete, this));
            this.isJump = true;
        }
    },

    onJumpComplete(){
        this.isJump = false;
        this.jumpAction = null;
        if(this.gameStatus == this.STATUS.LEFT)
        {
            this.player.node.scaleX = -1;
        }else
        {
            this.player.node.scaleX = 1;
        }
    },

    onDisable: function () {
       this.touch.node.off(cc.Node.EventType.TOUCH_START, this.onTouchEvent, this);
       this.player.node.off('playerCollision', this.onPlayerCollision,this);
    },
    
    update (dt) {
        if(this.gameOver === true)return;
        if(this.isJump && this.rateSpeed == 1)
        {
            this.player.node.runAction(this.jumpAction);
            this.rateSpeed = 0.5;
        }else if(this.isJump == false)
        {
            this.rateSpeed = 1;
        }

        this.rollLeftList();
        this.rollRightList();
        this.rollBg();
    },

    rollLeftList()
    {
        let speed = this.leftSpeed - this.rightSpeed;
        if(this.gameStatus == this.STATUS.RIGHT)
        {
            this.setCurrentSpeed(speed - this.reSpeed);
            this.moveList(this.leftFloorList, this.getCurrentSpeed());
            this.resizeRight(this.getCurrentSpeed(), this.leftFloorList, 196, this.leftFloorPosSet);
        }else if(this.colFloor)
        {
            let cha = this.colFloor.y - 82;
            this.reSpeed = 0;
            if(cha != 0)
            {
                if(Math.abs(speed) >= Math.abs(cha))
                {
                    this.moveList(this.leftFloorList, -cha);//修正
                }else
                {
                    this.reSpeed = cha > 0 ? speed : -speed;
                    this.moveList(this.leftFloorList, this.reSpeed);//修正
                    this.resizeRight(this.reSpeed, this.leftFloorList, 188, this.leftFloorPosSet);
                }
            }
            
        }
    },

    rollRightList()
    {
        let speed = this.rightSpeed - this.leftSpeed ;
        if(this.gameStatus == this.STATUS.LEFT)
        {
            this.setCurrentSpeed(speed - this.reSpeed);
            this.moveList(this.rightFloorList, this.getCurrentSpeed());
            this.resizeRight(this.getCurrentSpeed(), this.rightFloorList, 188, this.rightFloorPosSet);
        }else if(this.colFloor)
        {
            // let cha = this.rightFloorList[4].y - 82;
            let cha = this.colFloor.y - 82;
            this.reSpeed = 0;
            if(cha != 0)
            {
                if(Math.abs(speed) >= Math.abs(cha))
                {
                    this.moveList(this.rightFloorList, -cha);//修正
                }else
                {
                    this.reSpeed = cha > 0 ? -speed : speed;
                    this.moveList(this.rightFloorList, this.reSpeed);//修正
                    this.resizeRight(this.reSpeed, this.rightFloorList, 188, this.rightFloorPosSet);
                }
            }
        }
    },

    rollBg()
    {
        let s = this.bgSpeed - this.getCurrentSpeed() - this.reSpeed;

        //console.log('sudu  -------  s = ', s, ' currentspeed = ', this.getCurrentSpeed(), ' respeed = ' + this.reSpeed);

        let pointY = this.bg.y - s;
        if(pointY <= -960)pointY = 0;
        this.bg.y = pointY;
        this.addSpeed = this.score / 5000;
        this.score += s;
        this.scoreLabel.string = parseInt(this.score / 10);
    },

    moveList(list,speed)
    {
        for(let i = 0;i<list.length;i++)
        {
            let floor = list[i];
            floor.y += speed;
        }
    },
    
    resizeRight(speed,list,len,posSet)
    {
        let floor;
      
        if(speed < 0 && list[0].y < posSet[0] - 10)//最下面过界  10偏移量
        {
            floor = list.shift();
            floor.y = list[list.length - 1].y + len;
            list.push(floor);

        }else if(speed > 0 && list[list.length - 1].y > posSet[posSet.length - 1] + 10)
        {
            floor = list.pop();
            floor.y = list[0].y - len;
            list.unshift(floor);
        }
        this.resizeZIndex(list);
    },

    resizeZIndex(list)
    {
        for(let i = 0;i<list.length;i++)
        {
            let floor = list[i];
            floor.zIndex = i;
        }
    },

    getCurrentSpeed()
    {
        return this.currentSpeed * (1 + this.addSpeed);
    },

    setCurrentSpeed(speed)
    {
        this.currentSpeed = speed;
    }
    
});
